package com.zw.cloud.tools.controller.sse.emitter;


import com.zw.cloud.global.response.wrapper.annotation.NotNeedResponseAutoWrapper;
import com.zw.cloud.global.response.wrapper.entity.WebResult;
import com.zw.cloud.tools.utils.sse.emitter.SseEmitterUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * sse 长链接
 */
@RestController
@RequestMapping("/sse")
public class SseEmitterController {

    /**
     * 用于创建连接
     */
    @GetMapping("/connect/{userId}")
    @NotNeedResponseAutoWrapper
    public SseEmitter connect(@PathVariable String userId) {
        return SseEmitterUtils.connect(userId);
    }

    @GetMapping("/close/{userId}")
    @CrossOrigin
    public WebResult<Object> close(@PathVariable String userId) {
        SseEmitterUtils.removeUser(userId);
        return WebResult.success();
    }

    @GetMapping("/push/{userId}/{message}")
    //http://127.0.0.1:9040/sse/push/1693886285738/测试
    public WebResult<Boolean> push(@PathVariable String userId,@PathVariable(name = "message") String message) {
        return WebResult.success(SseEmitterUtils.sendMessage(userId, message));
    }

    /**
     * 推送给所有人
     */
    @GetMapping("/pushToAll/{message}")
    public WebResult<String> pushToAll(@PathVariable(name = "message") String message) {
        // 获取连接人数
        int userCount = SseEmitterUtils.getUserCount();
        // 如果无在线人数，返回
        if (userCount < 1) {
            return WebResult.fail("无人在线！");
        }
        SseEmitterUtils.batchSendMessage(message);
        return WebResult.success("发送成功！");
    }

}
